﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Estimate
{
    public partial class formProductRelocateDetail : FormMDIChildTemplate
    {
        public formProductRelocateDetail()
        {
            InitializeComponent();
        }

        readonly InvoiceRelocation invoiceRelocation;
        InvoiceWriteoff invoiceWriteoff;

        public formProductRelocateDetail(InvoiceRelocation invoiceRelocation)
        {
            InitializeComponent();
            this.invoiceRelocation = invoiceRelocation;
        }






        private void formMaterialProductRelocateDetail_Load(object sender, EventArgs e)
        {
            var storeHouse = invoiceRelocation.StoreHouse;
            string storeHouseName = "Невідомий Склад";
            if (storeHouse != null)
            {
                storeHouseName = storeHouse.StoreHouseName;
                invoiceWriteoff = GetInvoiceWriteoff();
            }


            Text = String.Format("Накладна №{0} від {1} з складу  [{2}] на склад [{3}]",
                                 invoiceRelocation.InvoiceRelocationNumber,
                                 invoiceRelocation.DateCreate.ToShortDateString(),
                                 storeHouseName,
                                 invoiceRelocation.StoreHouse1.StoreHouseName);

            
            TranslateGrid();
            if (invoiceRelocation.InvoiceIncome == null) FillProduct();

            FillInvoice();

        }

        private void TranslateGrid()
        {
            root.TranslateGrid(gridProduct);
            root.TranslateGrid(gridInvoice);
        }


        private InvoiceWriteoff GetInvoiceWriteoff()
        {

            var invoiceWriteOffs =
                context.InvoiceWriteoffs.Where(x => x.InvoiceRelocationID == invoiceRelocation.InvoiceRelocationID);
            if (invoiceWriteOffs.Count() == 0)
            {
                var invoiceWriteOff = new InvoiceWriteoff();
                invoiceWriteOff.InvoiceWriteoffNumber = 1;
                if (context.InvoiceWriteoffs.Count() > 0)
                    invoiceWriteOff.InvoiceWriteoffNumber =
                        context.InvoiceWriteoffs.Max(x => x.InvoiceWriteoffNumber) + 1;
                invoiceWriteOff.DateCreate = invoiceRelocation.DateCreate;
                invoiceWriteOff.StoreHouseID = invoiceRelocation.StoreHouseToID;
                invoiceWriteOff.Remark = "Накладна на Переміщення № " + invoiceRelocation.InvoiceRelocationNumber;
                invoiceWriteOff.InvoiceRelocation = invoiceRelocation;
                context.InvoiceWriteoffs.InsertOnSubmit(invoiceWriteOff);
                root.Submit(false);
                return invoiceWriteOff;
            }
            return invoiceWriteOffs.First();
        }

        private void FillProduct()
        {
            var storeHouse = invoiceRelocation.StoreHouse;
            IQueryable<Product> products = context.Products;

            if (textBoxProductName.Text.Length > 0)
                products = products.Where(x => x.ProductName.Contains(textBoxProductName.Text));
            if (textBoxProductCode.Text.Length > 0)
                products = products.Where(x => x.ProductCode.Contains(textBoxProductCode.Text));

            var productsInStoreHouse = products.Select
                (product => new ProductInStoreHouse
                                {
                                    ProductCategory = product.ProductCategory,
                                    ProductCode = product.ProductCode,
                                    ProductId = product.ProductID,
                                    ProductName = product.ProductName,
                                    Unit = product.Unit
                                }).ToList();
            foreach (var productInStoreHouse in productsInStoreHouse)
            {
                var cntIn =
                    storeHouse.ProductHistories.Where(
                        x =>
                        x.StatusID == 20 && x.StoreHouse == storeHouse &&
                        x.ProductID == productInStoreHouse.ProductId).Sum(
                        x => x.Cnt);
                var cntOut =
                    storeHouse.ProductHistories.Where(
                        x =>
                        x.StatusID == 30 && x.StoreHouse == storeHouse &&
                        x.ProductID == productInStoreHouse.ProductId).Sum(
                        x => x.Cnt);

                var cnt = cntIn - cntOut;

                productInStoreHouse.Count = cnt;
            }
            productInStoreHouseBindingSource.DataSource = productsInStoreHouse.Where(x => x.Count > 0).ToList();
        }

        private void textBoxProductCode_TextChanged(object sender, EventArgs e)
        { FillProduct(); }

        private void textBoxProductName_TextChanged(object sender, EventArgs e)
        { FillProduct(); }


        private void buttonAdd_Click(object sender, EventArgs e)
        {
            decimal price = context.InvoiceIncomePrices.OrderByDescending(x => x.DateSet).First().Price;
            decimal count = 0;
            try { count = decimal.Parse(textBoxCount.Text); }
            catch { return; }

            if (productInStoreHouseBindingSource.Current != null)
            {
                var productInStoreHouse = (ProductInStoreHouse) productInStoreHouseBindingSource.Current;
                Product product = context.Products.Where(x => x.ProductID == productInStoreHouse.ProductId ).First();
                if (count > productInStoreHouse.Count) return;

                var historyRelocation = new ProductHistory();
                historyRelocation.Cnt = count;
                historyRelocation.DateSet = invoiceRelocation.DateCreate;
                historyRelocation.Product = product;
                historyRelocation.StatusID = 20;
                historyRelocation.StoreHouse = invoiceRelocation.StoreHouse1;
                root.Submit(false);

                var invoiceRelocationToHistory = new InvoiceRelocationToHistory();
                invoiceRelocationToHistory.InvoiceRelocation = invoiceRelocation;
                invoiceRelocationToHistory.ProductHistory = historyRelocation;
                invoiceRelocationToHistory.Count = count;
                invoiceRelocationToHistory.Price = price * db.Dollar;
                invoiceRelocationToHistory.PriceTotal = decimal.Round(price * db.Dollar * count, 3);
                invoiceRelocationToHistory.InvoiceIncomeToHistory = null;
                root.Submit(false);

                var historyWriteOff = new ProductHistory();
                historyWriteOff.Cnt = count;
                historyWriteOff.DateSet = invoiceRelocation.DateCreate;
                historyWriteOff.Product = product;
                historyWriteOff.StatusID = 30;
                historyWriteOff.StoreHouse = invoiceRelocation.StoreHouse;
                root.Submit(false);

                var invoiceWriteoffToHistory = new InvoiceWriteoffToHistory();
                invoiceWriteoffToHistory.InvoiceWriteoff = invoiceWriteoff;
                invoiceWriteoffToHistory.ProductHistory = historyWriteOff;
                invoiceWriteoffToHistory.Count = count;
                invoiceWriteoffToHistory.Price = price * db.Dollar;
                invoiceWriteoffToHistory.PriceTotal = decimal.Round(price * db.Dollar* count, 3);
                invoiceWriteoffToHistory.InvoiceRelocationToHistory = invoiceRelocationToHistory;
                root.Submit();

                FillInvoice();
                FillProduct();

            }
        }

        private void FillInvoice()
        {
            var invoice = from invoiceRelocationToHistory in context.InvoiceRelocationToHistories
                          from histories in context.ProductHistories
                          where
                              invoiceRelocationToHistory.ProductHistory == histories &&
                              invoiceRelocationToHistory.InvoiceRelocation == invoiceRelocation
                          select new ProductInInvoice()
                                     {
                                         Count = invoiceRelocationToHistory.Count,
                                         InvoiceToHistoryID = invoiceRelocationToHistory.InvoiceRelocationToHistoryID,
                                         Price = invoiceRelocationToHistory.Price,
                                         PriceTotal = invoiceRelocationToHistory.PriceTotal,
                                         ProductName = histories.Product.ProductName,
                                         UnitName = histories.Product.Unit.UnitName
                                     };

            productInInvoiceBindingSource.DataSource = invoice.ToList();
        }





        private void buttonRemove_Click(object sender, EventArgs e)
        {
            var productInInvoice = (ProductInInvoice) productInInvoiceBindingSource.Current;
            if (productInInvoice != null)
                db.DeleteInvoiceRelocationToHistory
                    (db.GetInvoiceRelocationToHistory(productInInvoice.InvoiceToHistoryID));
            FillInvoice();
            FillProduct();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            var reportInvoiceRelocation = new reportInvoiceRelocation();

            reportInvoiceRelocation.DataSource = productInInvoiceBindingSource ;

            reportInvoiceRelocation.xrLabelFirm.Lines = db.GetFirmOwn().GetFullDescription();

            reportInvoiceRelocation.xrLabelHead1.Text = "Накладна на Переміщення № " + invoiceRelocation.InvoiceRelocationNumber;
            reportInvoiceRelocation.xrLabelHead2.Text = "від " + invoiceRelocation.DateCreate.ToShortDateString();

            if (invoiceRelocation.StoreHouse != null)
                reportInvoiceRelocation.xrLabelStoreHouseFrom.Text = invoiceRelocation.StoreHouse.StoreHouseName;
            reportInvoiceRelocation.xrLabelStoreHouseTo.Text = invoiceRelocation.StoreHouse1.StoreHouseName;
            reportInvoiceRelocation.xrLabelRemark.Text = invoiceRelocation.Remark;
            reportInvoiceRelocation.ShowPreview();
        }

    }
}
